//
//  showOnMapViewController.m
//  KG
//
//  Created by Eugene Braginets on 06.05.12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "showOnMapViewController.h"
#import "Place.h"
#import "bannerView.h"

@implementation showOnMapViewController
@synthesize place=_place;
@synthesize mapView = _mapView;
@synthesize bannerViewController=_bannerViewController;


- (id)initWithPlace:(Place *)place {
    self = [super initWithNibName:@"showOnMapViewController" bundle:nil];
    if (self) {
        NSLog(@"Place: %@",place.placeID);
        self.place=place;
        self.navigationItem.title=place.title;
    }
    return self;
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    NSLog(@"showOnMap memory warning");
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [self putAnnotations];
    bannerView *bannerVC=[[bannerView alloc] init];
    [self.view addSubview:bannerVC.view];
    [bannerVC animate];
    self.bannerViewController=bannerVC;
    
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
}

- (void)viewDidUnload
{
    [self setMapView:nil];
    UIView* v=[[self.view subviews] objectAtIndex:0];
    [v removeFromSuperview];
    v=nil;
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

#pragma mark - annotations 

- (void)putAnnotations {
	
    NSLog (@"remove previous annotations");
    
    for (Place* item in self.mapView.annotations) {
        if (![item isKindOfClass:[MKUserLocation class]])
            [self.mapView removeAnnotation:item];
    }
    
    NSLog (@"put new annotations");
    
	
        [self.mapView addAnnotation:self.place]; 
    	//Zoom up to fit all annotations
	//[self zoomToFitMapAnnotations];
	
	//center on user's location and make region
    //	[self gotoLocation];
    
    [self zoomToFitMapAnnotations];
}

- (void) gotoLocation {
    //centring map on user's location
    CLLocationCoordinate2D centerPoint;
    centerPoint=self.mapView.userLocation.location.coordinate;
    MKCoordinateRegion newRegion=MKCoordinateRegionMakeWithDistance (centerPoint, self.mapView.region.span.latitudeDelta, self.mapView.region.span.longitudeDelta);
    [self.mapView setRegion:newRegion animated:YES];
}

- (void)zoomToFitMapAnnotations {
    NSLog(@"zoom to fit annotations");
    int k=0;
    if([self.mapView.annotations count] == 0)
        return;
    if ([self.mapView.annotations count] ==1)
        k=1;
    NSLog (@"count: %d, k:%d",self.mapView.annotations.count,k);
    CLLocationCoordinate2D topLeftCoord;
    topLeftCoord.latitude = -90;
    topLeftCoord.longitude = 180;
    
    CLLocationCoordinate2D bottomRightCoord;
    bottomRightCoord.latitude = 90;
    bottomRightCoord.longitude = -180;
    
    for(Place* annotation in self.mapView.annotations)
    {
        topLeftCoord.longitude = fmin(topLeftCoord.longitude, annotation.coordinate.longitude);
        topLeftCoord.latitude = fmax(topLeftCoord.latitude, annotation.coordinate.latitude);
        
        bottomRightCoord.longitude = fmax(bottomRightCoord.longitude, annotation.coordinate.longitude);
        bottomRightCoord.latitude = fmin(bottomRightCoord.latitude, annotation.coordinate.latitude);
    }
    
    MKCoordinateRegion region;
    region.span.latitudeDelta = fabs(topLeftCoord.latitude - bottomRightCoord.latitude) * 1.2+0.05; // Add a little extra space on the sides
    region.span.longitudeDelta = fabs(bottomRightCoord.longitude - topLeftCoord.longitude) * 1.2+0.05; // Add a little extra space on the sides
    
    region.center.latitude = (topLeftCoord.latitude - (topLeftCoord.latitude - bottomRightCoord.latitude) * 0.5)+region.span.latitudeDelta*0.15; //slithly shift center
    region.center.longitude = (topLeftCoord.longitude + (bottomRightCoord.longitude - topLeftCoord.longitude) * 0.5)*1;
    
    //    region = [MKMapView regionThatFits:region];
    [self.mapView setRegion:region animated:YES];
    
}


#pragma mark - MKMapViewDelegate

-(void)  mapView:(MKMapView *)mapView 
didUpdateUserLocation:(MKUserLocation *)userLocation {
    NSLog (@"MKMAPVIEW lat: %f",userLocation.location.coordinate.latitude);
	NSLog (@"MKMAPVIEW lng: %f",userLocation.location.coordinate.longitude);
    //    NSLog (@"from appDelegate latitude: %f",[myAppDelegate location].coordinate.latitude);
    //    NSLog (@"from appDelegate longitude: %f",[myAppDelegate location].coordinate.longitude);
    
}


- (void)mapView:(MKMapView *)mapView_local regionDidChangeAnimated:(BOOL)animated {
    //	NSLog (@"Region changed");
    //	NSLog (@"MAP lat: %f",mapView_local.region.center.latitude);
    //	NSLog (@"MAP lng: %f",mapView_local.region.center.longitude);
    //	NSLog (@"size region: %f",mapView_local.region.span.latitudeDelta);
}


- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation
{
	NSLog (@"welcome to annotations!");
	
	// if it's the user location, just return nil.
    if ([annotation isKindOfClass:[MKUserLocation class]])
        return nil;
    
	// try to dequeue an existing pin view first
	static NSString* AnnotationIdentifier = @"AnnotationIdentifier";
	MKPinAnnotationView* pinView = [[MKPinAnnotationView alloc]
                                    initWithAnnotation:annotation reuseIdentifier:AnnotationIdentifier];
	pinView.canShowCallout=YES;
	
	UIButton *but=[UIButton buttonWithType:UIButtonTypeDetailDisclosure];
	[pinView setRightCalloutAccessoryView:but];
    
	[pinView setAnimatesDrop:NO];
    [pinView setPinColor:MKPinAnnotationColorGreen];
	
    //	pinView.image = [UIImage imageNamed:@"map_pin.png"];
    //    [pinView setContentScaleFactor:2];
    //    pinView.centerOffset = CGPointMake(0, -30);
    
	return pinView;
	
}

- (void)mapView:(MKMapView *)mapView annotationView:(MKAnnotationView *)view calloutAccessoryControlTapped:(UIControl *)control{
	
    [self.navigationController popViewControllerAnimated:YES];
//    PitchNewItemViewController *viewController = [[PitchNewItemViewController alloc] 
//                                                  initWithPlace:view.annotation];
//	[self.navigationController pushViewController:viewController animated:YES];
}





- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

@end
